﻿using PetaPoco;
using PetaPoco.Core;

namespace BlazorAdmin.Extensions
{
    /// <summary>
    /// PostgreSQL数据批量操作实现类
    /// </summary>
    internal class PostgreSQLBatchProvider : BatchProvider
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="db"></param>
        public PostgreSQLBatchProvider(IDatabase db) : base(db)
        { }

        /// <summary>
        /// 批次删除方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pd"></param>
        /// <param name="pocos"></param>
        protected override void DeleteBatch<T>(PocoData pd, IEnumerable<T> pocos)
        {
            string primaryKey = pd.TableInfo.PrimaryKey;
            IEnumerable<object?>? pks = pocos.ToPrimarys(primaryKey);
            List<object?>? list = null != pks ? pks.ToList() : default;
            if (null == list)
                return;
            //primaryKey = primaryKey.StartsWith("\"") ? primaryKey : $"\"{primaryKey}\"";
            try
            {
                Database.BeginTransaction();
                int start = 0;
                const int limit = 100;
                do
                {
                    IEnumerable<object?> ids = list.Skip(start).Take(limit);
                    Database.Delete<T>($"WHERE {primaryKey} IN (@ids)", new object[1] { new { ids } });
                    start += limit;
                }
                while (start < list.Count);
                Database.CompleteTransaction();
            }
            catch (Exception)
            {
                Database.AbortTransaction();
                throw;
            }
        }
    }
}
